<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 面包屑导航 -->
        <div v-if="$route.query.id" slot="header" class="clearfix">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>学科管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{ $route.query.name }}</el-breadcrumb-item>
            <el-breadcrumb-item>标签管理</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <!-- 搜索框位置 -->
        <el-form
          :inline="true"
          :model="query"
          class="demo-form-inline"
          style="display: flex"
        >
          <el-form-item label="标签名称">
            <el-input v-model="query.tagName" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="query.state" placeholder="请选择">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="small" @click="clearFn">清除</el-button>
            <el-button
              type="primary"
              size="small"
              @click="onSubmit"
            >搜索</el-button>
          </el-form-item>
          <el-form-item class="lastItem">
            <el-button
              v-if="$route.query.id"
              type="text"
              @click="$router.back()"
            >
              <i class="el-icon-back" />
              <span>返回学科</span>
            </el-button>
            <el-button type="success" size="small" @click="addTag">
              <span>新增标签</span>
            </el-button>
          </el-form-item>
        </el-form>
        <!-- 灰色地带 -->
        <el-tag
          type="info"
          class="eltag"
        ><i class="el-icon-info" /> 数据一共 {{ total }} 条</el-tag>
        <!-- 表格 -->
        <el-table
          :data="tagList"
          stripe
          style="width: 100%"
          :header-cell-style="headClass"
          :cell-style="rowClass"
        >
          <el-table-column type="index" width="100" label="序号" />
          <el-table-column prop="subjectName" label="所属学科" width="180" />
          <el-table-column prop="tagName" label="标签名称" width="180" />
          <el-table-column prop="username" label="创建者" />
          <el-table-column prop="addDate" label="创建日期">
            <template v-slot="scope">
              {{ rTime(scope.row.addDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="state" :formatter="formatState" label="状态" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button
                type="text"
                @click="changeState(scope.row.id, scope.row.state)"
              >{{ scope.row.state === 1 ? "禁用" : "启用" }}</el-button>
              <el-button
                type="text"
                :disabled="scope.row.state === 1"
                @click="editFn(scope.row)"
              >修改</el-button>
              <el-button
                type="text"
                :disabled="scope.row.state === 1"
                @click="delFn(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="block">
          <el-pagination
            background
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.pagesize"
            layout=" prev, pager, next, sizes, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <!-- 弹出框 -->
        <el-dialog
          :title="isEdit ? '修改标签' : '增加标签'"
          :visible.sync="showDialog"
          width="30%"
          @close="closeFn"
          @open="openFn"
        >
          <el-form ref="form" :model="form" label-width="80px" :rules="rules">
            <el-form-item v-if="!$route.query.id" label="所属学科" prop="subjectID">
              <el-select v-model="form.subjectID" placeholder="请选择">
                <el-option
                  v-for="item in subjectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="标签名称" prop="tagName">
              <el-input
                v-model="form.tagName"
                placeholder="请输入标签名称"
              />
            </el-form-item>
          </el-form>
          <div class="block">
            <el-button @click="showDialog = false">取 消</el-button>
            <el-button type="primary" @click="addTagFn">确 定</el-button>
          </div>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  list,
  changeState,
  add,
  detail,
  update,
  remove
} from '@/api/hmmm/tags'
import { simple } from '@/api/hmmm/subjects'
import { status } from '@/api/hmmm/constants'
export default {
  name: 'Tags',
  data() {
    return {
      tagList: [], // 渲染表格数据
      query: {
        page: 1,
        pagesize: 10
      },
      total: 0,
      showDialog: false, // 展示弹框
      form: {
        tagName: '',
        subjectID: '',
        subjectName: ''
      }, // 添加标签
      subjectList: [], // 学科列表
      isEdit: false, // 编辑状态
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        tagName: [
          { required: true, message: '标签名不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.list()
    console.log(this.$route.query.id)
  },
  methods: {
    // 删除标签
    async delFn(data) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该标签, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmRes === 'cancel') return this.$message('已取消')
      await remove(data)
      this.$message.success('删除成功')
      this.showDialog = false
      // 做删除一页最后一条功能
      if (this.tagList.length === 1) {
        this.query.page--
        if (this.query.page === 1) {
          this.query.page = 1
        }
      }
      this.list()
    },

    // 修改标签
    async editFn(id) {
      // 编辑表单先进行数据回填
      this.isEdit = true
      this.showDialog = true
      const res = await detail(id)
      this.form = res.data
    },

    // 关闭弹窗
    closeFn() {
      this.showDialog = false
      this.form = {
        tagName: '',
        subjectID: ''
      }
      this.$refs.form.resetFields()
    },

    // 弹窗打开事件
    async openFn() {
      const res = await simple()
      // 渲染下拉菜单
      this.subjectList = res.data
    },

    // 增加标签确定事件
    addTagFn() {
      this.$refs.form.validate(async(valid) => {
        if (!valid) return
        if (!this.isEdit) {
          if (this.$route.query.id) {
            await add({ subjectID: this.$route.query.id, ...this.form })
            this.$message.success('添加成功')
          } else {
            await add(this.form)
            this.$message.success('添加成功')
          }
        } else {
          // 编辑发送编辑请求
          if (this.$route.query.id) {
            await update({ subjectID: this.$route.query.id, ...this.form })
            this.$message.success('更改成功')
          } else {
            await update(this.form)
            this.$message.success('更改成功')
          }
        }
        this.list()
        this.closeFn()
        this.isEdit = false
      })
    },

    // 增加标签按钮
    addTag() {
      this.showDialog = true
    },

    // 修改id对应状态
    async changeState(id, state) {
      const data = {
        id,
        state: 0
      }
      if (state === 0) {
        data.state = 1
      } else {
        data.state = 0
      }
      await changeState(data)
      this.$message.success('操作成功')
      this.list()
    },

    // 清空搜索框
    clearFn() {
      this.query = {
        page: 1,
        pagesize: 10
      }
    },

    // 格式化状态(枚举数据)
    formatState(row, column, cellValue, index) {
      // cellValue为后台返回的值
      const obj = status.find((item) => item.value === cellValue)
      if (obj.value === 1) {
        return '已启用'
      } else {
        return '已禁用'
      }
    },

    // 获取列表
    async list() {
      if (this.$route.query.id || this.$route.query.name) {
        this.query.subjectID = this.$route.query.id
        const res2 = await list(this.query)
        console.log(res2)
        this.tagList = res2.data.items
        this.total = res2.data.counts
      } else {
        const res = await list(this.query)
        console.log(res)
        this.tagList = res.data.items
        this.total = res.data.counts
      }
    },

    // 上方搜索按钮
    onSubmit() {
      this.list()
    },

    // 控制每页多少条
    handleSizeChange(val) {
      this.query.pagesize = val
      this.list()
      this.query.page = 1
    },

    // 翻页
    handleCurrentChange(val) {
      this.query.page = val
      this.list()
    },

    // 表头样式
    headClass() {
      return 'background:#f4f4f5;border-bottom:solid 1px #a4acbb;'
    },

    // 单元格样式
    rowClass() {
      return 'color: black;'
    },

    // 时间转换
    rTime(date) {
      var jsondate = new Date(date).toJSON()
      return new Date(+new Date(jsondate) + 8 * 3600 * 1000)
        .toISOString()
        .replace(/T/g, ' ')
        .replace(/\.[\d]{3}Z/, '')
    }
  }
}
</script>

<style scoped>
.el-form-item {
  margin-left: 18px;
}
.el-table {
  color: #a4acbb;
  font-weight: 500;
}
.eltag {
  width: 100%;
  height: 40px;
  font-size: 15px;
  line-height: 40px;
  margin: 0 0 20px 0;
}
.block {
  text-align: right;
  margin-top: 40px;
}
.el-select {
  width: 100%;
}
.lastItem {
  text-align: right;
  display: inline-block;
  flex: 1;
}
</style>
